package com.tiance.web.controller.back;

import com.tiance.base.LoginToken;
import com.tiance.base.ShiroUser;
import com.tiance.base.ShiroVO;
import com.tiance.enums.OperateTypeEnum;
import com.tiance.exception.BusinessException;
import com.tiance.shiro.utils.ShiroUtil;
import com.tiance.web.aspect.OperatorControllerLog;
import com.tiance.web.captcha.Captcha;
import com.tiance.web.captcha.SpecCaptcha;
import com.tiance.web.controller.base.BackController;
import com.tiance.web.controller.base.FrontController;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author 雷霆
 * @version 1.0.0
 * @date$ 2019/1/30
 *
 * Description：
 *
 * Modification History:
 *
 */
@Controller
public class HomeController extends BackController {

    @RequestMapping(value="/login",method = RequestMethod.GET)
    public String toLogin(HttpServletRequest request, ShiroVO shiroVO){

        Subject currentUser = SecurityUtils.getSubject();
        if(currentUser.isAuthenticated()){
          return "back/index";
        }
        return "back/login";
    }

    @RequestMapping(value="/loginOut.action",method = RequestMethod.GET)
    public String loginOut(HttpServletRequest request, ShiroVO shiroVO){
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        return "back/login";
    }


    @RequestMapping(value="/login",method = RequestMethod.POST)
    @OperatorControllerLog(operationLogType= OperateTypeEnum.BACK_INTERFACE,operationName="登录")
    public String login(HttpServletRequest request, ShiroVO shiroVO) throws Exception{
        String prefix = "HomeController-login--->";
        logger.info(prefix + "进入方法");
        String msg = "";


        try {
            //如果已登录，则不再验证
            Subject currentUser = SecurityUtils.getSubject();
            if(currentUser.isAuthenticated()){
                return "back/index";
            }
            request.setAttribute("userName",shiroVO.getUserName());
            LoginToken token = new LoginToken(shiroVO.getUserName(), shiroVO.getPassWord());


            currentUser.login(token);
            if(currentUser.isAuthenticated()){//如果登录成功
                //登录成功，记录登录日志
                //ShiroUser shiroUser = ShiroUtil.getUserNotNull();
                // LogManager.me().executeLog(LogTaskFactory.loginLog(shiroUser.getId(), ""));
                //   ShiroUtil.getSession().setAttribute("sessionFlag", true);


            }



        } catch (UnknownAccountException e) {
            logger.error(prefix + "UnknownAccountException -- > 账号不存在：");
            msg = "账号不存在";
            request.setAttribute("msg",msg);
            return "back/login";
        } catch(IncorrectCredentialsException e) {
            logger.error(prefix + "IncorrectCredentialsException -- > 密码不正确：");
            msg = "密码不正确";
            request.setAttribute("msg",msg);
            return "back/login";
        } catch (ConcurrentAccessException e) {
            logger.error(String.format("user has been authenticated: %s", shiroVO.getUserName()), e);
        } catch (AuthenticationException e) {
            logger.error(String.format("account except: %s", shiroVO.getUserName()), e);
            request.setAttribute("msg",e.getMessage());
            return "back/login";
        }catch (BusinessException e){
            logger.error(prefix + "BusinessException -- > 业务异常：",e);
            request.setAttribute("msg",e.getMessage());
            return "back/login";
        }catch (Throwable e){
            logger.error(prefix + "BusinessException -- > 系统异常：",e);
            request.setAttribute("msg","系统异常，请联系后台管理人员");
            return "back/login";
        }

        return "back/index";
    }

    @RequestMapping("/403")
    public String unauthorizedRole(){
        logger.error("------没有权限-------");
        return "403";
    }

    @GetMapping({ "gifCode", "/index/gifCode"})
    public void getGifCode(HttpServletResponse response, HttpServletRequest request) {
        try {
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.setContentType("image/gif");

            Session session = SecurityUtils.getSubject().getSession();
//            Captcha captcha = new GifCaptcha(140, 30, 4);
            Captcha captcha = new SpecCaptcha(140, 30, 4);

            captcha.out(response.getOutputStream());

            session.removeAttribute("_code");
            session.setAttribute("_code", captcha.text().toLowerCase());
        } catch (Exception e) {
            logger.info("getGifCode-获取到异常："+e);
        }
    }


    @RequestMapping("home/index")
    public String homeIndex(HttpServletRequest request){

        ShiroUser shiroUser = ShiroUtil.getUser();




/*
        // 如果是管理员，并且没有修改过密码，就跳转到重置密码页
        if (shiroUser.getRoleType().equals(RoleEnum.ADMIN.getCode())) {
            String isModifyPwd = user.getIsModifyPwd();
            if (isModifyPwd == null || !isModifyPwd.equals(OperatorIsModifyPwdEnum.TRUE.getCode())) {
                // 跳转到修改密码页
                request.setAttribute("operatorId", user.getId());
                // 登录页跳转的，就增加变量-isLoginCome
                logger.info("homeIndex-首页接口-获取到当前用户没有重置过密码,跳转到重置密码页");
                request.setAttribute("isLoginCome", true);
                return "accountManage/resetPwd";
            }
        }*/

        return "back/homePage";

    }


}